package golang

func getSkyline(buildings [][]int) [][]int {

	blocks := [][]int{}

	for i := range buildings {
		stepInsertBuilding(blocks, buildings[i])
	}

	return blocksToSkyline(blocks)
}

func stepInsertBuilding(blocks [][]int, building []int) {
	left := building[0]
	right := building[1]
	height := building[2]

	if len(blocks) <= 0 {
		blocks = append(blocks, building)
		return
	}

	touchBlocks := [][]int{}

	//找到接触的blocks
	for i := range blocks {
		b := blocks[i]

		bLeft := b[0]
		bRight := b[1]

		//在新的building内部
		if bLeft >= left && bRight <= right {
			touchBlocks = append(touchBlocks, b)
		}

		//与新building有接触
		if left >= bLeft && left <= bRight {
			touchBlocks = append(touchBlocks, b)
		} else if right >= bLeft && right <= bRight {
			touchBlocks = append(touchBlocks, b)
		}
	}

	touchBlocks = append(touchBlocks, building)

	return
}

func blocksToSkyline(blocks [][]int) [][]int {
	points := [][]int{}
	for i := range blocks {
		points = append(points, []int{blocks[i][0], blocks[i][2]})
	}

	if len(blocks) > 0 {
		last := len(blocks) - 1
		points = append(points, []int{blocks[last][1], 0})
	}

	return points
}
